import pandas as pd
import numpy as np
from datetime import datetime
import openpyxl as px
import calendar
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
import logging
from tkinter.scrolledtext import ScrolledText
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib
matplotlib.use('TkAgg')
plt.style.use('seaborn-v0_8')  # 使用更现代的样式
matplotlib.rcParams['font.sans-serif'] = ['SimHei']  # 设置中文字体
matplotlib.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题

# 设置日志
logging.basicConfig(
    filename='zcq_analysis.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

class ZCQAnalyzer:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("中长期交易盈亏分析系统")
        self.root.geometry("900x700")  # 稍微增加窗口大小
        
        # 设置主题颜色
        self.style = ttk.Style()
        self.style.configure('TLabel', font=('微软雅黑', 10))
        self.style.configure('TButton', font=('微软雅黑', 10))
        self.style.configure('TEntry', font=('微软雅黑', 10))
        self.style.configure('Heading.TLabel', font=('微软雅黑', 12, 'bold'))
        
        # 自定义按钮样式
        self.style.configure('Action.TButton',
                           padding=10,
                           font=('微软雅黑', 10, 'bold'))
        
        # 自定义Frame样式
        self.style.configure('Card.TFrame', 
                           background='#ffffff',
                           relief='solid',
                           borderwidth=1)
        
        self.style.configure('MainFrame.TFrame',
                           background='#f0f0f0')
        
        # 添加新的样式
        self.style.configure('Info.TLabel',
                           font=('微软雅黑', 10),
                           foreground='#2196F3')
        self.style.configure('Error.TLabel',
                           font=('微软雅黑', 10),
                           foreground='#F44336')
        
        # 初始化变量
        self.year_var = tk.StringVar(value="2025")
        self.month_var = tk.StringVar()
        self.file_path = tk.StringVar()
        self.output_path = tk.StringVar(value="盈亏分析")
        
        # 添加交易选择变量
        self.selected_trade = tk.StringVar()
        self.trade_result = None  # 存储分析结果
        
        self.canvas = None  # 添加画布属性
        
        self.setup_ui()
        
        # 确保默认输出目录存在
        os.makedirs(self.output_path.get(), exist_ok=True)
        logging.info("程序启动，创建默认输出目录")

    def setup_ui(self):
        # 创建主框架
        main_frame = ttk.Frame(self.root, padding="20", style='MainFrame.TFrame')
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 标题
        title_label = ttk.Label(main_frame, 
                              text="中长期交易盈亏分析系统", 
                              style='Heading.TLabel')
        title_label.grid(row=0, column=0, columnspan=4, pady=(0, 20))
        
        # 创建输入框架
        input_frame = ttk.Frame(main_frame, padding="15", style='Card.TFrame')
        input_frame.grid(row=1, column=0, columnspan=4, sticky=(tk.W, tk.E), pady=(0, 15))
        
        # 年份和月份选择行
        date_frame = ttk.Frame(input_frame)
        date_frame.grid(row=0, column=0, columnspan=4, pady=(0, 10))
        
        ttk.Label(date_frame, text="年份:").grid(row=0, column=0, padx=(0, 5))
        year_entry = ttk.Entry(date_frame, textvariable=self.year_var, width=8)
        year_entry.grid(row=0, column=1, padx=(0, 20))
        
        ttk.Label(date_frame, text="月份:").grid(row=0, column=2, padx=(0, 5))
        month_combo = ttk.Combobox(date_frame, textvariable=self.month_var, width=5)
        month_combo['values'] = tuple(range(1, 13))
        month_combo.grid(row=0, column=3)
        
        # 文件选择框架
        file_frame = ttk.Frame(input_frame, padding="10")
        file_frame.grid(row=1, column=0, columnspan=4, sticky=(tk.W, tk.E))
        
        # 输入文件选择
        ttk.Label(file_frame, text="中长期持仓文件:").grid(row=0, column=0, sticky=tk.W, padx=(0, 5), pady=5)
        ttk.Entry(file_frame, textvariable=self.file_path, width=50).grid(row=0, column=1, padx=5, pady=5)
        ttk.Button(file_frame, text="浏览", command=self.select_file).grid(row=0, column=2, padx=5, pady=5)
        
        # 输出文件夹选择
        ttk.Label(file_frame, text="输出文件夹:").grid(row=1, column=0, sticky=tk.W, padx=(0, 5), pady=5)
        ttk.Entry(file_frame, textvariable=self.output_path, width=50).grid(row=1, column=1, padx=5, pady=5)
        ttk.Button(file_frame, text="浏览", command=self.select_output_folder).grid(row=1, column=2, padx=5, pady=5)
        
        # 操作按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=2, column=0, columnspan=4, pady=15)
        
        # 分析按钮
        ttk.Button(button_frame, 
                  text="开始分析", 
                  command=self.start_analysis, 
                  style='Action.TButton',
                  width=20).grid(row=0, column=0, padx=10)
                  
        ttk.Button(button_frame, 
                  text="退出程序", 
                  command=self.root.quit,
                  style='Action.TButton', 
                  width=20).grid(row=0, column=1, padx=10)
        
        # 添加交易分析框架
        trade_analysis_frame = ttk.Frame(main_frame, padding="15", style='Card.TFrame')
        trade_analysis_frame.grid(row=3, column=0, columnspan=4, sticky=(tk.W, tk.E), pady=15)
        
        # 交易选择区域
        trade_select_frame = ttk.Frame(trade_analysis_frame)
        trade_select_frame.grid(row=0, column=0, columnspan=4, pady=(0, 10))
        
        ttk.Label(trade_select_frame, text="选择交易类型:").grid(row=0, column=0, padx=(0, 5))
        self.trade_combo = ttk.Combobox(trade_select_frame, 
                                      textvariable=self.selected_trade,
                                      state='readonly',
                                      width=30)
        self.trade_combo.grid(row=0, column=1, padx=5)
        
        # 创建图表显示区域
        self.chart_frame = ttk.Frame(trade_analysis_frame)
        self.chart_frame.grid(row=1, column=0, columnspan=4, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 创建数据摘要区域
        self.summary_frame = ttk.Frame(trade_analysis_frame)
        self.summary_frame.grid(row=2, column=0, columnspan=4, sticky=(tk.W, tk.E), pady=(10, 0))
        
        # 绑定选择事件
        self.trade_combo.bind('<<ComboboxSelected>>', self.show_trade_analysis)
        
        # 将原有的log_frame移到trade_analysis_frame后面
        log_frame = ttk.Frame(main_frame, padding="15", style='Card.TFrame')
        log_frame.grid(row=4, column=0, columnspan=4, sticky=(tk.W, tk.E, tk.N, tk.S), pady=15)
        
        # 日志标题
        ttk.Label(log_frame, text="运行日志", style='Heading.TLabel').grid(row=0, column=0, sticky=tk.W, pady=(0, 10))
        
        # 日志文本框
        self.log_text = ScrolledText(log_frame, 
                                   height=20, 
                                   width=80,
                                   font=('Consolas', 9),
                                   background='#fafafa',
                                   relief='flat')
        self.log_text.grid(row=1, column=0, padx=5, pady=5)
        
        # 状态栏
        status_frame = ttk.Frame(main_frame, style='Card.TFrame')
        status_frame.grid(row=5, column=0, columnspan=4, sticky=(tk.W, tk.E))
        self.status_label = ttk.Label(status_frame, 
                                    text="就绪",
                                    padding=(10, 5))
        self.status_label.grid(row=0, column=0, sticky=tk.W)
        
        # 配置日志处理器
        self.setup_log_handler()
        
        # 配置网格权重
        self.root.grid_rowconfigure(0, weight=1)
        self.root.grid_columnconfigure(0, weight=1)
        main_frame.grid_columnconfigure(0, weight=1)

    def setup_log_handler(self):
        # 创建自定义日志处理器
        class TextHandler(logging.Handler):
            def __init__(self, text_widget):
                logging.Handler.__init__(self)
                self.text_widget = text_widget
                
            def emit(self, record):
                msg = self.format(record)
                self.text_widget.insert(tk.END, msg + '\n')
                self.text_widget.see(tk.END)
                
        # 添加处理器到日志系统
        text_handler = TextHandler(self.log_text)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        text_handler.setFormatter(formatter)
        logging.getLogger().addHandler(text_handler)

    def select_file(self):
        filename = filedialog.askopenfilename(
            title="选择中长期持仓文件",
            filetypes=[("Excel files", "*.xlsx *.xls")]
        )
        if filename:
            self.file_path.set(filename)
            logging.info(f"选择文件: {filename}")

    def select_output_folder(self):
        """选择输出文件夹"""
        folder = filedialog.askdirectory(
            title="选择输出文件夹",
            initialdir=self.output_path.get()
        )
        if folder:
            self.output_path.set(folder)
            logging.info(f"选择输出文件夹: {folder}")

    def validate_inputs(self):
        try:
            month = int(self.month_var.get())
            if not (1 <= month <= 12):
                messagebox.showerror("错误", "请选择有效的月份(1-12)")
                logging.error("无效的月份输入")
                return False
                
            if not self.file_path.get():
                messagebox.showerror("错误", "请选择中长期持仓文件")
                logging.error("未选择输入文件")
                return False
                
            return True
        except ValueError:
            messagebox.showerror("错误", "请输入有效的月份")
            logging.error("月份输入格式错误")
            return False

    def update_status(self, message):
        """更新状态栏信息"""
        self.status_label.config(text=message)
        self.root.update()

    def start_analysis(self):
        if not self.validate_inputs():
            return
            
        try:
            self.update_status("分析中...")
            logging.info("开始分析...")
            # 设置全局变量
            global file_zcq, n_month
            file_zcq = self.file_path.get()
            n_month = int(self.month_var.get())
            
            # 执行原有的分析流程
            year = int(self.year_var.get())  # 从界面获取年度值
            _, max_day = calendar.monthrange(year, n_month)
            df_date = self.zcq(n_month)
            logging.info("生成基础数据完成")
            
            # 继续执行原有的分析流程...
            tf = self.year_zcq(df_date, '年度多月电量', n_month)
            wb = px.load_workbook(file_zcq)
            sheet_names = wb.sheetnames
            
            df1 = tf
            for sheet in sheet_names:
                if sheet.startswith('外送') or '国网'  or '转让' in sheet:
                    df1 = self.ws_zcq(df1, sheet, n_month, max_day)
                    logging.info(f"处理工作表 {sheet} 完成")
            
            # 执行其他分析步骤...
            df1 = self.jz_yue(df1, '月、旬集中竞价', n_month, '月度集中竞价')
            df1 = self.jz_sx(df1, '月、旬集中竞价', n_month, '上旬集中竞价')
            df1 = self.jz_zx(df1, '月、旬集中竞价', n_month, '中旬集中竞价')
            df1 = self.jz_xx(df1, '月、旬集中竞价', n_month, '下旬集中竞价')
            df1 = self.jz_yue(df1, '月、旬滚动撮合', n_month, '月度滚动撮合')
            df1 = self.jz_sx(df1, '月、旬滚动撮合', n_month, '上旬滚动撮合')
            df1 = self.jz_zx(df1, '月、旬滚动撮合', n_month, '中旬滚动撮合')
            df1 = self.jz_xx(df1, '月、旬滚动撮合', n_month, '下旬滚动撮合')
            df1 = self.rgd(df1, '日滚动', n_month)
            
            # df从第6列开始，第6列与第7列相乘，第8列与第9列相乘，一直到最后一列与倒数第二列相乘，然后相加，形成新的一列，列名为"中长期交易收入"
            df1['中长期交易收入'] = df1.iloc[:, 5::2].mul(df1.iloc[:, 6::2].values).sum(axis=1)
            # 将df中所有包含交易电量的列相加，形成新的一列，列名为"中长期交易电量"
            df1['中长期交易电量'] = df1.filter(like='交易电量').sum(axis=1)
            # 将中长期交易收入与中长期交易电量相除，形成新的一列，列名为"中长期电价"
            df1['中长期电价'] = df1['中长期交易收入'] / df1['中长期交易电量']
            # 将df1中增加日前电量
            df1 = self.rqjg(df1, '日前现货价格（按调控折算后填）', max_day)
            # 计算盈亏情况
            
            df1['年度中长期盈亏'] = df1['年度中长期-交易电量'] * (df1['年度中长期-电价'] - df1['日前价格']) # 年度中长期盈亏
            df1['度电年度中长期盈亏'] = df1['年度中长期盈亏'].div(df1['年度中长期-交易电量'], fill_value=0) # 度电年度盈亏
            
            # 计算外送、转让和月度国网相关的盈亏计算
            # 获取所有相关交易电量列
            trading_cols = [col for col in df1.columns if col.endswith('-交易电量') and 
                            ('外送' in col or '转让' in col or '国网' in col)]
            
            for col in trading_cols:
                # 从列名中提取基础名称（例如"外送1"、"转让1"或"月度国网"）
                base_name = col.split('-')[0]
                
                try:
                    if '国网' in base_name:
                        # 月度国网盈亏计算（不扣除输电费）
                        df1[f'{base_name}盈亏'] = (
                            df1[f'{base_name}-交易电量'] * 
                            (df1[f'{base_name}-电价'] - df1['日前价格'])
                        )
                    else:
                        # 外送和转让盈亏计算（扣除输电费）
                        df1[f'{base_name}盈亏'] = (
                            df1[f'{base_name}-交易电量'] * 
                            (df1[f'{base_name}-电价'] - df1['日前价格']) 
                        )
                    
                    # 计算度电盈亏 = 盈亏/交易电量
                    df1[f'度电{base_name}盈亏'] = df1.apply(
                        lambda x: x[f'{base_name}盈亏'] / x[f'{base_name}-交易电量'] 
                        if x[f'{base_name}-交易电量'] != 0 
                        else 0, 
                        axis=1)
                    
                except Exception as e:
                    print(f"处理{base_name}时出错: {str(e)}")
            
            # 计算各类盈亏和度电盈亏
            df1['月度分时盈亏'] = df1['月度集中竞价-交易电量'] * (df1['月度集中竞价-电价'] - df1['日前价格']) + df1['月度滚动撮合-交易电量'] * (df1['月度滚动撮合-电价'] - df1['日前价格']) # 月度分时交易盈亏
            df1['上旬分时盈亏'] = df1['上旬集中竞价-交易电量'] * (df1['上旬集中竞价-电价'] - df1['日前价格']) + df1['上旬滚动撮合-交易电量'] * (df1['上旬滚动撮合-电价'] - df1['日前价格']) # 上旬分时交易盈亏
            df1['中旬分时盈亏'] = df1['中旬集中竞价-交易电量'] * (df1['中旬集中竞价-电价'] - df1['日前价格']) + df1['中旬滚动撮合-交易电量'] * (df1['中旬滚动撮合-电价'] - df1['日前价格']) # 中旬分时交易盈亏
            df1['下旬分时盈亏'] = df1['下旬集中竞价-交易电量'] * (df1['下旬集中竞价-电价'] - df1['日前价格']) + df1['下旬滚动撮合-交易电量'] * (df1['下旬滚动撮合-电价'] - df1['日前价格']) # 下旬分时交易盈亏
            df1['日滚动盈亏'] = df1['日滚动撮合-交易电量'] * (df1['日滚动撮合-电价'] - df1['日前价格']) # 日滚动盈亏
            df1['中长期盈亏'] = df1['中长期交易电量'] * (df1['中长期电价'] - df1['日前价格']) # 中长期盈亏
            
            # 计算度电盈亏，先将电量和添加为新列，然后进行条件判断
            # 月度分时度电盈亏
            df1['月度分时电量和'] = df1['月度集中竞价-交易电量'] + df1['月度滚动撮合-交易电量']
            df1['度电月度分时盈亏'] = df1.apply(lambda x: x['月度分时盈亏'] / x['月度分时电量和'] if x['月度分时电量和'] != 0 else 0, axis=1)
            df1 = df1.drop('月度分时电量和', axis=1)  # 计算完成后删除临时列
            
            # 上旬分时度电盈亏
            df1['上旬分时电量和'] = df1['上旬集中竞价-交易电量'] + df1['上旬滚动撮合-交易电量']
            df1['度电上旬分时盈亏'] = df1.apply(lambda x: x['上旬分时盈亏'] / x['上旬分时电量和'] if x['上旬分时电量和'] != 0 else 0, axis=1)
            df1 = df1.drop('上旬分时电量和', axis=1)
            
            # 中旬分时度电盈亏
            df1['中旬分时电量和'] = df1['中旬集中竞价-交易电量'] + df1['中旬滚动撮合-交易电量']
            df1['度电中旬分时盈亏'] = df1.apply(lambda x: x['中旬分时盈亏'] / x['中旬分时电量和'] if x['中旬分时电量和'] != 0 else 0, axis=1)
            df1 = df1.drop('中旬分时电量和', axis=1)
            
            # 下旬分时度电盈亏
            df1['下旬分时电量和'] = df1['下旬集中竞价-交易电量'] + df1['下旬滚动撮合-交易电量']
            df1['度电下旬分时盈亏'] = df1.apply(lambda x: x['下旬分时盈亏'] / x['下旬分时电量和'] if x['下旬分时电量和'] != 0 else 0, axis=1)
            df1 = df1.drop('下旬分时电量和', axis=1)
            
            # 日滚动度电盈亏
            df1['度电日滚动盈亏'] = df1.apply(lambda x: x['日滚动盈亏'] / x['日滚动撮合-交易电量'] 
                                          if x['日滚动撮合-交易电量'] != 0 else 0, axis=1)
            
            # 中长期度电盈亏
            df1['度电中长期盈亏'] = df1.apply(lambda x: x['中长期盈亏'] / x['中长期交易电量'] 
                                          if x['中长期交易电量'] != 0 else 0, axis=1)
            
            # 修改输出路径
            output_file = os.path.join(self.output_path.get(), f'{n_month}月中长期盈亏分析.xlsx')
            file_path = os.path.join(self.output_path.get(), f'{n_month}月中长期盈亏分析.xlsx')
            df1.to_excel(output_file, index=False)
            #在输出的文件中新建一个工作表，按照日期汇总各项电量度电盈亏
            transaction_columns = [col for col in df1.columns if col.endswith('-交易电量')]
            profit_loss_pairs = []
            for tc in transaction_columns:
                transaction_type = tc.split('-交易电量')[0].strip()
                pl_col = f'{transaction_type}盈亏'
                if pl_col in df1.columns:
                    profit_loss_pairs.append((tc, pl_col))

                # 按日期分组汇总
                grouped = df1.groupby('日期').agg(
                    {**{tc: 'sum' for tc, _ in profit_loss_pairs},
                    **{pl: 'sum' for _, pl in profit_loss_pairs},
                    '月度分时盈亏': 'sum',
                    '上旬分时盈亏': 'sum',
                    '中旬分时盈亏': 'sum',
                    '下旬分时盈亏': 'sum',
                    '月度集中竞价-交易电量': 'sum',
                    '月度滚动撮合-交易电量': 'sum',
                    '上旬集中竞价-交易电量': 'sum',
                    '上旬滚动撮合-交易电量': 'sum',
                    '中旬集中竞价-交易电量': 'sum',
                    '中旬滚动撮合-交易电量': 'sum',
                    '下旬集中竞价-交易电量': 'sum',
                    '下旬滚动撮合-交易电量': 'sum'}
                )

                # 计算按日期汇总的分时度电盈亏
                grouped['月度分时电量和'] = grouped['月度集中竞价-交易电量'] + grouped['月度滚动撮合-交易电量']
                grouped['度电月度分时盈亏'] = grouped.apply(lambda x: x['月度分时盈亏'] / x['月度分时电量和'] if x['月度分时电量和'] != 0 else 0, axis=1)
                
                grouped['上旬分时电量和'] = grouped['上旬集中竞价-交易电量'] + grouped['上旬滚动撮合-交易电量']
                grouped['度电上旬分时盈亏'] = grouped.apply(lambda x: x['上旬分时盈亏'] / x['上旬分时电量和'] if x['上旬分时电量和'] != 0 else 0, axis=1)
                
                grouped['中旬分时电量和'] = grouped['中旬集中竞价-交易电量'] + grouped['中旬滚动撮合-交易电量']
                grouped['度电中旬分时盈亏'] = grouped.apply(lambda x: x['中旬分时盈亏'] / x['中旬分时电量和'] if x['中旬分时电量和'] != 0 else 0, axis=1)
                
                grouped['下旬分时电量和'] = grouped['下旬集中竞价-交易电量'] + grouped['下旬滚动撮合-交易电量']
                grouped['度电下旬分时盈亏'] = grouped.apply(lambda x: x['下旬分时盈亏'] / x['下旬分时电量和'] if x['下旬分时电量和'] != 0 else 0, axis=1)

                # 删除临时列
                grouped = grouped.drop(['月度分时电量和', '上旬分时电量和', '中旬分时电量和', '下旬分时电量和'], axis=1)

                # 按分时段类型汇总
                grouped_fs = df1.groupby('分时段类型').agg({
                    # 月度分时
                    '月度集中竞价-交易电量': 'sum',
                    '月度滚动撮合-交易电量': 'sum',
                    '月度分时盈亏': 'sum',
                    # 上旬分时
                    '上旬集中竞价-交易电量': 'sum',
                    '上旬滚动撮合-交易电量': 'sum',
                    '上旬分时盈亏': 'sum',
                    # 中旬分时
                    '中旬集中竞价-交易电量': 'sum',
                    '中旬滚动撮合-交易电量': 'sum',
                    '中旬分时盈亏': 'sum',
                    # 下旬分时
                    '下旬集中竞价-交易电量': 'sum',
                    '下旬滚动撮合-交易电量': 'sum',
                    '下旬分时盈亏': 'sum',
                    # 日滚动
                    '日滚动撮合-交易电量': 'sum',
                    '日滚动盈亏': 'sum'
                })

                # 计算各时段的电量和与度电盈亏
                # 月度
                grouped_fs['月度分时电量和'] = grouped_fs['月度集中竞价-交易电量'] + grouped_fs['月度滚动撮合-交易电量']
                grouped_fs['度电月度分时盈亏'] = grouped_fs.apply(
                    lambda x: x['月度分时盈亏'] / x['月度分时电量和'] if x['月度分时电量和'] != 0 else 0, 
                    axis=1
                )

                # 上旬
                grouped_fs['上旬分时电量和'] = grouped_fs['上旬集中竞价-交易电量'] + grouped_fs['上旬滚动撮合-交易电量']
                grouped_fs['度电上旬分时盈亏'] = grouped_fs.apply(
                    lambda x: x['上旬分时盈亏'] / x['上旬分时电量和'] if x['上旬分时电量和'] != 0 else 0, 
                    axis=1
                )

                # 中旬
                grouped_fs['中旬分时电量和'] = grouped_fs['中旬集中竞价-交易电量'] + grouped_fs['中旬滚动撮合-交易电量']
                grouped_fs['度电中旬分时盈亏'] = grouped_fs.apply(
                    lambda x: x['中旬分时盈亏'] / x['中旬分时电量和'] if x['中旬分时电量和'] != 0 else 0, 
                    axis=1
                )

                # 下旬
                grouped_fs['下旬分时电量和'] = grouped_fs['下旬集中竞价-交易电量'] + grouped_fs['下旬滚动撮合-交易电量']
                grouped_fs['度电下旬分时盈亏'] = grouped_fs.apply(
                    lambda x: x['下旬分时盈亏'] / x['下旬分时电量和'] if x['下旬分时电量和'] != 0 else 0, 
                    axis=1
                )

                # 日滚动
                grouped_fs['度电日滚动盈亏'] = grouped_fs.apply(
                    lambda x: x['日滚动盈亏'] / x['日滚动撮合-交易电量'] if x['日滚动撮合-交易电量'] != 0 else 0, 
                    axis=1
                )

                
                # 在start_analysis方法中，在现有的grouped_fs计算之后添加新的分时交易汇总计算
                grouped_fs['分时电量交易和'] = (
                    grouped_fs['月度集中竞价-交易电量'] + 
                    grouped_fs['月度滚动撮合-交易电量'] +
                    grouped_fs['上旬集中竞价-交易电量'] + 
                    grouped_fs['上旬滚动撮合-交易电量'] +
                    grouped_fs['中旬集中竞价-交易电量'] + 
                    grouped_fs['中旬滚动撮合-交易电量'] +
                    grouped_fs['下旬集中竞价-交易电量'] + 
                    grouped_fs['下旬滚动撮合-交易电量']
                )

                grouped_fs['分时电量盈亏'] = (
                    grouped_fs['月度分时盈亏'] +
                    grouped_fs['上旬分时盈亏'] +
                    grouped_fs['中旬分时盈亏'] +
                    grouped_fs['下旬分时盈亏']
                )

                # 计算度电分时盈亏
                grouped_fs['度电分时盈亏'] = grouped_fs.apply(
                    lambda x: x['分时电量盈亏'] / x['分时电量交易和'] if x['分时电量交易和'] != 0 else 0,
                    axis=1
                )

                # 创建新的分时交易分时段汇总表
                fs_summary = grouped_fs[[
                    '分时电量交易和',
                    '分时电量盈亏',
                    '度电分时盈亏'
                ]].round(2)  # 将所有数值四舍五入到2位小数
            
            # 在现有的grouped_fs计算之后添加新的计算
            # 获取所有外送、国网相关的交易电量列
            ws_cols = [col for col in df1.columns if col.endswith('-交易电量') and 
                       ('外送' in col or '国网' in col)]
            
            for col in ws_cols:
                # 从列名中提取基础名称(例如"外送1"或"月度国网")
                base_name = col.split('-')[0].strip()
                
                # 计算外送、国网的电量和与度电盈亏
                grouped_fs[f'{base_name}-交易电量'] = df1.groupby('分时段类型')[col].sum()
                grouped_fs[f'{base_name}盈亏'] = df1.groupby('分时段类型')[f'{base_name}盈亏'].sum()
                grouped_fs[f'度电{base_name}盈亏'] = grouped_fs.apply(
                    lambda x: x[f'{base_name}盈亏'] / x[f'{base_name}-交易电量'] if x[f'{base_name}-交易电量'] != 0 else 0,
                    axis=1
                )
            
            # 年度中长期电量分析
            grouped_fs['年度中长期-交易电量'] = df1.groupby('分时段类型')['年度中长期-交易电量'].sum() 
            grouped_fs['年度中长期盈亏'] = df1.groupby('分时段类型')['年度中长期盈亏'].sum()
            grouped_fs['度电年度中长期盈亏'] = grouped_fs.apply(
                lambda x: x['年度中长期盈亏'] / x['年度中长期-交易电量'] if x['年度中长期-交易电量'] != 0 else 0,
                axis=1  
            )
            
            with pd.ExcelWriter(output_file, engine='openpyxl', mode='a') as writer:
                    if '日期汇总度电盈亏' in writer.book.sheetnames:
                        del writer.book['日期汇总度电盈亏']
                    if '分时段汇总度电盈亏' in writer.book.sheetnames:
                        del writer.book['分时段汇总度电盈亏']
                    if '分时交易分时段汇总盈亏表' in writer.book.sheetnames:
                        del writer.book['分时交易分时段汇总盈亏表']

                    grouped.to_excel(writer, sheet_name='日期汇总度电盈亏')
                    grouped_fs.to_excel(writer, sheet_name='分时段汇总度电盈亏')
                    fs_summary.to_excel(writer, sheet_name='分时交易分时段汇总盈亏表')
                        
            self.update_status("分析完成")
            logging.info("分析完成")
            messagebox.showinfo("成功", f"分析完成！\n结果已保存到: {output_file}")
            
            # 保存分析结果用于后续显示
            self.trade_result = df1
            
            # 更新交易类型下拉框
            trade_columns = [col.split('-')[0] for col in df1.columns 
                           if col.endswith('-交易电量')]
            self.trade_combo['values'] = trade_columns
            
        except Exception as e:
            self.update_status("分析出错")
            logging.error(f"分析过程中出错: {str(e)}", exc_info=True)
            messagebox.showerror("错误", f"分析过程中出错: {str(e)}")

    def run(self):
        self.root.mainloop()

    def zcq(self, month):
        """中长期持仓分析"""
        try:
            df_list = []
            year = int(self.year_var.get())
            _, max_day = calendar.monthrange(year, month)
            
            logging.info(f"开始生成{month}月持仓数据")
            
            # 遍历日期和时段
            for day in range(1, max_day + 1):
                for minute in range(15, 24 * 60 + 15, 15):
                    hour_1 = minute // 60
                    hour = (minute-15) // 60
                    minute %= 60
                    
                    if hour_1 != 24:
                        if hour == 23:              
                            if minute == 0:
                                df_list.append(pd.DataFrame({
                                    '月份': [month], 
                                    '日期': [day],
                                    '小时': [f'{hour%24:02d}'],
                                    '分钟': [f'{(hour+1)%24:02d}:{minute:02d}'],
                                    '分时段类型': ['23:00-24:00']
                                }))
                            else:
                                df_list.append(pd.DataFrame({
                                    '月份': [month], 
                                    '日期': [day],
                                    '小时': [f'{hour%24:02d}'],
                                    '分钟': [f'{hour%24:02d}:{minute:02d}'],
                                    '分时段类型': ['23:00-24:00']
                                }))
                        else:
                            if minute == 0:
                                df_list.append(pd.DataFrame({
                                    '月份': [month], 
                                    '日期': [day],
                                    '小时': [f'{hour%24:02d}'],
                                    '分钟': [f'{(hour+1)%24:02d}:{minute:02d}'],
                                    '分时段类型': [f'{hour%24:02d}:00-{(hour+1)%24:02d}:00']
                                }))
                            else:
                                df_list.append(pd.DataFrame({
                                    '月份': [month], 
                                    '日期': [day],
                                    '小时': [f'{hour%24:02d}'],
                                    '分钟': [f'{hour%24:02d}:{minute:02d}'],
                                    '分时段类型': [f'{hour%24:02d}:00-{(hour+1)%24:02d}:00']
                                }))
                    else:
                        df_list.append(pd.DataFrame({
                            '月份': [month], 
                            '日期': [day],
                            '小时': ['23'],
                            '分钟': ['24:00'],
                            '分时段类型': ['23:00-24:00']
                        }))
                    
            df = pd.concat(df_list, ignore_index=True)
            logging.info("持仓数据生成完成")
            return df
        
        except Exception as e:
            logging.error(f"生成持仓数据时出错: {str(e)}")
            raise

    def year_zcq(self, df1, sheet_name, n_month):
        """年度中长期电量分析"""
        try:
            logging.info("开始年度中长期电量分析")
            df2 = pd.read_excel(self.file_path.get(), sheet_name=sheet_name, header=1)
            df2 = df2.iloc[1:25]
            
            df1['年度中长期-交易电量'] = None
            df1['年度中长期-电价'] = None
            
            df1 = df1.merge(df2[['分时段类型', '交易电量', '电价']], 
                           how='left', 
                           left_on='分时段类型', 
                           right_on='分时段类型')
            
            df1.loc[df1['月份'] == n_month, '年度中长期-交易电量'] = df1['交易电量']/4
            df1.loc[df1['月份'] == n_month, '年度中长期-电价'] = df1['电价']
            
            df1 = df1.drop(['交易电量', '电价'], axis=1)
            logging.info("年度中长期电量分析完成")
            return df1
        
        except Exception as e:
            logging.error(f"年度中长期电量分析出错: {str(e)}")
            raise

    def ws_zcq(self, df1, sheet_name, n_month, max_day):
        """外送中长期电量分析"""
        try:
            logging.info(f"开始处理{sheet_name}工作表")
            wb = px.load_workbook(self.file_path.get())
            ws = wb[sheet_name]
            
            # 检查E36、C36和B2-B32的值
            if (ws['E36'].value == 0 or ws['E36'].value is None or 
                ws['C36'].value is None or any(ws[f'B{i}'].value is None for i in range(2, 33))):
                wb.close()
                return df1
            
            # 获取交易名称并确保是字符串类型，然后去除空格
            ws_name1 = str(ws['C36'].value).strip()  # 先转换为字符串，再去除空格
            ws_price1 = ws['A2'].value
            wb.close()
            
            logging.info(f"开始处理{sheet_name}工作表")
            wb = px.load_workbook(self.file_path.get())
            ws = wb[sheet_name]

            # 检查E36、C36和B2-B32的值
            if (ws['E36'].value == 0 or ws['E36'].value is None or 
                ws['C36'].value is None or any(ws[f'B{i}'].value is None for i in range(2, 33))):
                wb.close()
                return df1

            ws_name1 = ws['C36'].value
            ws_price1 = ws['A2'].value
            wb.close()

            df3 = pd.read_excel(self.file_path.get(), 
                               sheet_name=sheet_name, 
                               header=37, 
                               usecols='B:AG')
            df3 = df3.iloc[:, 0:max_day+1]

            # 检查是否包含 '日期' 列
            if '日期' not in df3.columns:
                logging.error(f"工作表 {sheet_name} 缺少 '日期' 列")
                return df1

            # 保存原始的分时段类型列
            time_periods = df3['日期'].copy()

            df3 = pd.melt(df3, 
                          id_vars=['日期'], 
                          value_vars=df3.columns[1:], 
                          var_name='日', 
                          value_name='交易电量')

            df3.columns = ['分时段类型', '日期', '交易电量']
            df3['月份'] = pd.to_datetime(df3['日期']).dt.month
            df3['日期'] = pd.to_datetime(df3['日期']).dt.day

            # 添加新列
            if '国网' in sheet_name:
                col_prefix = ''
            elif '转让' in sheet_name:
                col_prefix = '转让'
            else:
                col_prefix = '外送'

            new_col_name = f'{col_prefix}{ws_name1}' if col_prefix else ws_name1
            df1[f'{new_col_name}-交易电量'] = None
            df1[f'{new_col_name}-电价'] = None
            
            df1 = df1.merge(df3[['分时段类型', '月份', '日期', '交易电量']], 
                           how='left', 
                           left_on=['分时段类型', '月份', '日期'], 
                           right_on=['分时段类型', '月份', '日期'])
            
            mask = df1['月份'] == n_month
            df1.loc[mask, f'{new_col_name}-交易电量'] = df1['交易电量']/4
            df1.loc[mask, f'{new_col_name}-电价'] = ws_price1
            
            df1 = df1.drop(['交易电量'], axis=1)
            logging.info(f"{sheet_name}处理完成")
            return df1
        
        except Exception as e:
            logging.error(f"处理{sheet_name}时出错: {str(e)}")
            raise

    def jz_yue(self, df1, sheet_name, n_month, y_name):
        """月度集中竞价分析"""
        try:
            logging.info(f"开始{y_name}分析")
            df3 = pd.read_excel(self.file_path.get(), 
                               sheet_name=sheet_name, 
                               usecols='B:F', 
                               skiprows=2, 
                               nrows=24)
            
            df3.columns = ['分时段类型', '月份', '交易电量', '电量', '电价']
            df3 = df3.drop(['月份', '电量'], axis=1)
            
            df1[f'{y_name}-交易电量'] = None
            df1[f'{y_name}-电价'] = None
            
            df1 = df1.merge(df3[['分时段类型', '交易电量', '电价']], 
                           how='left', 
                           left_on='分时段类型', 
                           right_on='分时段类型')
            
            df1.loc[df1['月份'] == n_month, f'{y_name}-交易电量'] = df1['交易电量']/4
            df1.loc[df1['月份'] == n_month, f'{y_name}-电价'] = df1['电价']
            
            df1 = df1.drop(['交易电量', '电价'], axis=1)
            logging.info(f"{y_name}分析完成")
            return df1
        
        except Exception as e:
            logging.error(f"{y_name}分析出错: {str(e)}")
            raise

    def jz_sx(self, df1, sheet_name, n_month, y_name):
        """上旬集中竞价分析"""
        try:
            logging.info(f"开始{y_name}分析")
            df3 = pd.read_excel(self.file_path.get(), 
                               sheet_name=sheet_name, 
                               usecols='I:M', 
                               skiprows=2, 
                               nrows=24)
            
            df3.columns = ['分时段类型', '月份', '交易电量', '电量', '电价']
            df3 = df3.drop(['月份', '电量'], axis=1)
            
            df1[f'{y_name}-交易电量'] = None
            df1[f'{y_name}-电价'] = None
            
            df1 = df1.merge(df3[['分时段类型', '交易电量', '电价']], 
                           how='left', 
                           left_on='分时段类型', 
                           right_on='分时段类型')
            
            mask = (df1['月份'] == n_month) & (df1['日期'] <= 10)
            df1.loc[mask, f'{y_name}-交易电量'] = df1['交易电量']/4
            df1.loc[mask, f'{y_name}-电价'] = df1['电价']
            
            df1 = df1.drop(['交易电量', '电价'], axis=1)
            logging.info(f"{y_name}分析完成")
            return df1
        
        except Exception as e:
            logging.error(f"{y_name}分析出错: {str(e)}")
            raise

    def jz_zx(self, df1, sheet_name, n_month, y_name):
        """中旬集中竞价分析"""
        try:
            logging.info(f"开始{y_name}分析")
            df3 = pd.read_excel(self.file_path.get(), 
                               sheet_name=sheet_name, 
                               usecols='P:T', 
                               skiprows=2, 
                               nrows=24)
            
            df3.columns = ['分时段类型', '月份', '交易电量', '电量', '电价']
            df3 = df3.drop(['月份', '电量'], axis=1)
            
            df1[f'{y_name}-交易电量'] = None
            df1[f'{y_name}-电价'] = None
            
            df1 = df1.merge(df3[['分时段类型', '交易电量', '电价']], 
                           how='left', 
                           left_on='分时段类型', 
                           right_on='分时段类型')
            
            mask = (df1['月份'] == n_month) & (df1['日期'] > 10) & (df1['日期'] <= 20)
            df1.loc[mask, f'{y_name}-交易电量'] = df1['交易电量']/4
            df1.loc[mask, f'{y_name}-电价'] = df1['电价']
            
            df1 = df1.drop(['交易电量', '电价'], axis=1)
            logging.info(f"{y_name}分析完成")
            return df1
        
        except Exception as e:
            logging.error(f"{y_name}分析出错: {str(e)}")
            raise

    def jz_xx(self, df1, sheet_name, n_month, y_name):
        """下旬集中竞价分析"""
        try:
            logging.info(f"开始{y_name}分析")
            df3 = pd.read_excel(self.file_path.get(), 
                               sheet_name=sheet_name, 
                               usecols='W:AA', 
                               skiprows=2, 
                               nrows=24)
            
            df3.columns = ['分时段类型', '月份', '交易电量', '电量', '电价']
            df3 = df3.drop(['月份', '电量'], axis=1)
            
            df1[f'{y_name}-交易电量'] = None
            df1[f'{y_name}-电价'] = None
            
            df1 = df1.merge(df3[['分时段类型', '交易电量', '电价']], 
                           how='left', 
                           left_on='分时段类型', 
                           right_on='分时段类型')
            
            mask = (df1['月份'] == n_month) & (df1['日期'] > 20)
            df1.loc[mask, f'{y_name}-交易电量'] = df1['交易电量']/4
            df1.loc[mask, f'{y_name}-电价'] = df1['电价']
            
            df1 = df1.drop(['交易电量', '电价'], axis=1)
            logging.info(f"{y_name}分析完成")
            return df1
        
        except Exception as e:
            logging.error(f"{y_name}分析出错: {str(e)}")
            raise

    def rgd(self, df1, sheet_name, n_month):
        """日滚动撮合分析"""
        try:
            logging.info("开始日滚动撮合分析")
            tf = pd.read_excel(self.file_path.get(), 
                              sheet_name=sheet_name, 
                              header=1, 
                              skiprows=1, 
                              nrows=25)
            tf = tf.iloc[1:]
            
            tfs = []
            start_col = 1
            
            for i in range(0, 31):
                end_col = start_col + 5
                tf2 = tf.iloc[:, start_col:end_col]
                start_col = end_col + 2
                
                tf2.columns = ['分时段类型', '现货价格', '盈亏', '交易电量', '电价']
                tf2['日期'] = i + 1
                tfs.append(tf2)
                
            tf3 = pd.concat(tfs)
            tf3['月份'] = n_month
            tf3 = tf3.reindex(columns=['月份', '日期', '分时段类型', '现货价格', 
                                      '盈亏', '交易电量', '电价'])
            
            df1['日滚动撮合-交易电量'] = None
            df1['日滚动撮合-电价'] = None
            
            df1 = df1.merge(tf3[['月份', '日期', '分时段类型', '交易电量', '电价']], 
                           how='left', 
                           left_on=['月份', '日期', '分时段类型'], 
                           right_on=['月份', '日期', '分时段类型'])
            
            df1['日滚动撮合-交易电量'] = df1['交易电量']/4
            df1['日滚动撮合-电价'] = df1['电价']
            
            df1 = df1.drop(['交易电量', '电价'], axis=1)
            logging.info("日滚动撮合分析完成")
            return df1
        
        except Exception as e:
            logging.error(f"日滚动撮合分析出错: {str(e)}")
            raise

    def rqjg(self, df1, sheet_name, max_day):
        """日前价格分析"""
        try:
            logging.info("开始日前价格分析")
            df = pd.read_excel(self.file_path.get(), 
                              sheet_name=sheet_name, 
                              usecols='A:AF', 
                              nrows=97)
            df = df.iloc[:, 0:max_day+1]
            
            df = pd.melt(df, 
                         id_vars=['时间'], 
                         value_vars=df.columns[1:], 
                         var_name='日', 
                         value_name='日前价格')
            
            df = df.dropna(subset=['时间'])
            df.rename(columns={'时间': '分钟'}, inplace=True)
            df['日期'] = pd.to_datetime(df['日']).dt.day
            
            df1['日前价格'] = None
            df1 = df1.merge(df[['日期', '分钟', '日前价格']], 
                           how='left', 
                           left_on=['日期', '分钟'], 
                           right_on=['日期', '分钟'])
            
            df1 = df1.drop(['日前价格_x'], axis=1)
            df1.rename(columns={'日前价格_y': '日前价格'}, inplace=True)
            
            logging.info("日前价格分析完成")
            return df1
        
        except Exception as e:
            logging.error(f"日前价格分析出错: {str(e)}")
            raise

    def show_trade_analysis(self, event=None):
        """显示所选交易的分析结果"""
        if (self.trade_result is None or 
            self.trade_result.empty or 
            not self.selected_trade.get()):
            return
            
        selected = self.selected_trade.get()
        df = self.trade_result
        
        try:
            # 清除现有图表
            for widget in self.chart_frame.winfo_children():
                widget.destroy()
            for widget in self.summary_frame.winfo_children():
                widget.destroy()
                
            # 获取相关列名
            volume_col = f"{selected}-交易电量"
            price_col = f"{selected}-电价"
            
            # 根据交易类型确定盈亏列名
            if '集中竞价' in selected:
                profit_col = f"{selected.replace('集中竞价', '')}分时盈亏"
                unit_profit_col = f"度电{selected.replace('集中竞价', '')}分时盈亏"
            elif '滚动撮合' in selected:
                profit_col = f"{selected.replace('滚动撮合', '')}分时盈亏"
                unit_profit_col = f"度电{selected.replace('滚动撮合', '')}分时盈亏"
            else:
                profit_col = f"{selected}盈亏"
                unit_profit_col = f"度电{selected}盈亏"
            
            # 计算汇总数据
            total_volume = df[volume_col].sum()
            total_profit = df[profit_col].sum()
            avg_unit_profit = total_profit / total_volume if total_volume != 0 else 0
            
            # 创建汇总标签
            summary_labels = [
                f"总交易电量: {total_volume:,.2f} MWh",
                f"总盈亏金额: {total_profit:,.2f} 元",
                f"平均度电盈亏: {avg_unit_profit:.4f} 元/kWh"
            ]
            
            for i, text in enumerate(summary_labels):
                ttk.Label(self.summary_frame, 
                         text=text,
                         style='Info.TLabel',
                         padding=(10, 5)).grid(row=0, column=i, padx=10)
            
            # 获取分时段统计数据
            time_stats = df.groupby('分时段类型').agg({
                volume_col: 'sum',
                profit_col: 'sum'
            })
            
            # 计算度电盈亏
            time_stats[unit_profit_col] = time_stats.apply(
                lambda x: x[profit_col] / x[volume_col] if x[volume_col] != 0 else 0,
                axis=1
            )
            
            # 创建缩略图
            thumbnail_fig = Figure(figsize=(8, 6), dpi=80)
            thumbnail_fig.suptitle(f'{selected}交易分析\n(点击查看详细图表)', 
                                 fontsize=12, fontweight='bold')
            
            # 在缩略图中创建一个简单的概览图
            ax = thumbnail_fig.add_subplot(111)
            ax.plot(range(len(time_stats)), time_stats[volume_col], 
                   label='交易电量', color='blue')
            ax2 = ax.twinx()
            ax2.plot(range(len(time_stats)), time_stats[profit_col], 
                    label='盈亏金额', color='red')
            
            ax.set_xticks(range(len(time_stats)))
            ax.set_xticklabels(time_stats.index, rotation=45, ha='right')
            ax.set_ylabel('交易电量 (MWh)', color='blue')
            ax2.set_ylabel('盈亏金额 (元)', color='red')
            
            lines1, labels1 = ax.get_legend_handles_labels()
            lines2, labels2 = ax2.get_legend_handles_labels()
            ax.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
            
            thumbnail_fig.tight_layout()
            
            # 创建缩略图画布
            thumbnail_canvas = FigureCanvasTkAgg(thumbnail_fig, master=self.chart_frame)
            thumbnail_canvas.draw()
            thumbnail_widget = thumbnail_canvas.get_tk_widget()
            thumbnail_widget.pack(fill=tk.BOTH, expand=True)
            
            # 绑定点击事件
            thumbnail_widget.bind('<Button-1>', lambda e: self.show_detailed_charts(
                df, selected, time_stats, volume_col, price_col, profit_col, unit_profit_col))
            
        except Exception as e:
            ttk.Label(self.summary_frame, 
                     text=f"分析出错: {str(e)}",
                     style='Error.TLabel').grid(row=0, column=0)
            logging.error(f"交易分析显示出错: {str(e)}")

    def show_detailed_charts(self, df, selected, time_stats, volume_col, price_col, profit_col, unit_profit_col):
        """显示详细图表窗口"""
        # 创建新窗口
        detail_window = tk.Toplevel(self.root)
        detail_window.title(f"{selected}交易详细分析")
        detail_window.geometry("1200x800")
        
        # 创建主框架
        main_frame = ttk.Frame(detail_window, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 创建图表框架
        chart_frame = ttk.Frame(main_frame)
        chart_frame.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 创建详细图表
        fig = Figure(figsize=(12, 8), dpi=100)
        fig.suptitle(f'{selected}交易详细分析', fontsize=16, fontweight='bold', y=0.95)
        
        # 电量图表
        ax1 = fig.add_subplot(221)
        bars1 = ax1.bar(range(len(time_stats)), time_stats[volume_col], 
                       color='skyblue', alpha=0.7)
        ax1.set_title('分时段交易电量', pad=15, fontsize=12)
        ax1.set_xlabel('时段', fontsize=10)
        ax1.set_ylabel('电量 (MWh)', fontsize=10)
        ax1.set_xticks(range(len(time_stats)))
        ax1.set_xticklabels(time_stats.index, rotation=45, ha='right')
        
        # 添加数值标签
        for bar in bars1:
            height = bar.get_height()
            ax1.text(bar.get_x() + bar.get_width()/2., height,
                    f'{height:,.0f}',
                    ha='center', va='bottom', fontsize=8)
        
        # 盈亏图表
        ax2 = fig.add_subplot(222)
        bars2 = []
        for i, value in enumerate(time_stats[profit_col]):
            color = 'lightgreen' if value >= 0 else 'lightcoral'
            bar = ax2.bar(i, value, color=color, alpha=0.7)
            bars2.append(bar[0])
        
        ax2.set_title('分时段盈亏金额', pad=15, fontsize=12)
        ax2.set_xlabel('时段', fontsize=10)
        ax2.set_ylabel('盈亏 (元)', fontsize=10)
        ax2.set_xticks(range(len(time_stats)))
        ax2.set_xticklabels(time_stats.index, rotation=45, ha='right')
        ax2.axhline(y=0, color='black', linestyle='-', linewidth=0.5)
        
        # 添加数值标签
        for bar in bars2:
            height = bar.get_height()
            va = 'bottom' if height >= 0 else 'top'
            ax2.text(bar.get_x() + bar.get_width()/2., height,
                    f'{height:,.0f}',
                    ha='center', va=va, fontsize=8)
        
        # 度电盈亏图表
        ax3 = fig.add_subplot(223)
        x = range(len(time_stats))
        y = time_stats[unit_profit_col]
        
        # 分别绘制正值和负值
        pos_mask = y >= 0
        neg_mask = y < 0
        
        ax3.plot(x[pos_mask], y[pos_mask], 'go-', linewidth=2, markersize=8, label='正盈亏')
        ax3.plot(x[neg_mask], y[neg_mask], 'ro-', linewidth=2, markersize=8, label='负盈亏')
        
        ax3.set_title('分时段度电盈亏', pad=15, fontsize=12)
        ax3.set_xlabel('时段', fontsize=10)
        ax3.set_ylabel('度电盈亏 (元/kWh)', fontsize=10)
        ax3.set_xticks(range(len(time_stats)))
        ax3.set_xticklabels(time_stats.index, rotation=45, ha='right')
        ax3.grid(True, linestyle='--', alpha=0.7)
        ax3.axhline(y=0, color='black', linestyle='-', linewidth=0.5)
        ax3.legend()
        
        # 添加数值标签
        for i, value in enumerate(time_stats[unit_profit_col]):
            va = 'bottom' if value >= 0 else 'top'
            ax3.text(i, value, f'{value:.1f}', 
                    ha='center', va=va, fontsize=8)
        
        # 日前价格对比图表
        ax4 = fig.add_subplot(224)
        df_daily = df.groupby('日期').agg({
            price_col: 'mean',
            '日前价格': 'mean'
        })
        
        # 绘制价格曲线
        line1, = ax4.plot(df_daily.index, df_daily[price_col], 
                          'bo-', label='交易价格', linewidth=2, markersize=6)
        line2, = ax4.plot(df_daily.index, df_daily['日前价格'], 
                          'rs-', label='日前价格', linewidth=2, markersize=6)
        
        # 添加数值标签
        for x, y in zip(df_daily.index, df_daily[price_col]):
            ax4.text(x, y, f'{y:.2f}', ha='center', va='bottom', fontsize=8)
        for x, y in zip(df_daily.index, df_daily['日前价格']):
            ax4.text(x, y, f'{y:.2f}', ha='center', va='top', fontsize=8)
        
        ax4.set_title('日前价格对比', pad=15, fontsize=12)
        ax4.set_xlabel('日期', fontsize=10)
        ax4.set_ylabel('价格 (元/kWh)', fontsize=10)
        ax4.legend(loc='best')
        ax4.grid(True, linestyle='--', alpha=0.7)
        
        # 调整x轴刻度，确保显示所有日期
        ax4.set_xticks(df_daily.index)
        ax4.tick_params(axis='x', rotation=45)
        
        # 优化图表布局
        fig.tight_layout(rect=[0, 0.03, 1, 0.92])
        
        # 添加图表到窗口
        canvas = FigureCanvasTkAgg(fig, master=chart_frame)
        canvas.draw()
        canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
        
        # 添加数据表格
        table_frame = ttk.Frame(main_frame, padding="10")
        table_frame.grid(row=2, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 创建表格
        tree = ttk.Treeview(table_frame, columns=('时段', '交易电量', '盈亏金额', '度电盈亏'))
        tree.heading('时段', text='时段')
        tree.heading('交易电量', text='交易电量 (MWh)')
        tree.heading('盈亏金额', text='盈亏金额 (元)')
        tree.heading('度电盈亏', text='度电盈亏 (元/kWh)')
        
        # 添加数据到表格
        for idx in time_stats.index:
            tree.insert('', 'end', values=(
                idx,
                f"{time_stats.loc[idx, volume_col]:,.2f}",
                f"{time_stats.loc[idx, profit_col]:,.2f}",
                f"{time_stats.loc[idx, unit_profit_col]:.4f}"
            ))
        
        tree.pack(fill=tk.BOTH, expand=True)
        
        # 配置窗口大小调整
        detail_window.grid_rowconfigure(0, weight=1)
        detail_window.grid_columnconfigure(0, weight=1)
        main_frame.grid_rowconfigure(1, weight=3)
        main_frame.grid_rowconfigure(2, weight=1)
        main_frame.grid_columnconfigure(0, weight=1)

if __name__ == "__main__":
    app = ZCQAnalyzer()
    app.run()